import numpy as np
import csv
import random
from datetime import datetime
from time import strftime

'''
Global and Local Empirical Bayes Smoothers with Gamma Model
'''

def getCurTime():
    """
    get current time
    Return value of the date string format(%Y-%m-%d %H:%M:%S)
    """
    format='%Y-%m-%d %H:%M:%S'
    sdate = None
    cdate = datetime.now()
    try:
        sdate = cdate.strftime(format)
    except:
        raise ValueError
    return sdate

def build_data_list(inputCSV):
    sKey = []
    fn = inputCSV
    ra = csv.DictReader(file(fn), dialect="excel")
    
    for record in ra:
        #print record[ra.fieldnames[0]], type(record[ra.fieldnames[-1]])
        #for item in ra.fieldnames:
            #temp = float(record[item])
        ostate = int(record[ra.fieldnames[0]])
        ocounty = int(record[ra.fieldnames[1]])
        dstate = int(record[ra.fieldnames[2]])
        dcounty = int(record[ra.fieldnames[3]])
        
        sKey.append(year)
        sKey.append(formateFIPS(ostate, ocounty)[0])
        sKey.append(formateFIPS(ostate, ocounty)[1])
        sKey.append(formateFIPS(ostate, ocounty)[2])
        sKey.append(formateFIPS(dstate, dcounty)[0])
        sKey.append(formateFIPS(dstate, dcounty)[1])
        sKey.append(formateFIPS(dstate, dcounty)[2])
        sKey.append(int(record[ra.fieldnames[-3]]))
        sKey.append(int(record[ra.fieldnames[-2]]))
        sKey.append(int(record[ra.fieldnames[-1]]))
    sKey = np.array(sKey)
    sKey.shape=(-1,10)
    return sKey

def formateFIPS(stateid, countyid):
    stateid = str(int(stateid))
    if len(stateid) < 2:
        stateid = '0' + stateid

    countyid = str(int(countyid))
    if len(countyid) < 2:
        countyid = '00' + countyid
    elif len(countyid) < 3:
        countyid = '0' + countyid

    return [stateid, countyid, stateid+countyid]

#--------------------------------------------------------------------------
#MAIN

if __name__ == "__main__":
    print "begin at " + getCurTime()

    year = 2008

    filepath = 'C:/_DATA/migration89_08/COUNTY Migration/countyinflow0809.csv'
    data = build_data_list(filepath)

    np.savetxt(filepath[:-4] + '_formate.csv', data, delimiter=',', fmt = '%s')
    